import { Form, Input,Button, message } from 'antd'
import { apiLogin } from '../api'
import Cookie from 'js-cookie'
import { useNavigate } from 'react-router-dom'

const Login = () => {

    const navigate = useNavigate();

    // data:默认值：用户在输入框中输入的内容
    const onFinish = (data) => {
        apiLogin(data).then(res => {
            // 获取到的token 保存到本地
            Cookie.set('token', res.token)

            // 登录成功提示
            message.success('登录成功')

            // 跳转到首页
            window.location.href = '/'
        })
    }

    // 跳转到注册页面
    const toSign = () => {
        navigate('/sign')
    }

    return <div>
        <Form
            onFinish={onFinish} // 校验成功的回调函数
        >
            <Form.Item
                label="用户名"
                name="username"
                rules={[
                    { required: true, message: '请输入用户名称' }
                ]}
            >
                <Input />
            </Form.Item>

            <Form.Item
                label="密码"
                name="password"
                rules={[
                    { required: true, message: '请输入密码' }
                ]}
            >
                <Input />
            </Form.Item>

            <Form.Item>
                <Button type="primary" htmlType="submit" > 登录 </Button>
                <Button onClick={toSign}>去注册</Button>
            </Form.Item>
        </Form>
    </div>
}

export default Login